<template>
  <div>
    <el-tabs v-model="searchForm.tab" class="demo-tabs" @tab-change="getData">
      <el-tab-pane
        v-for="(item, index) in tabbars"
        :key="index"
        :label="item.name"
        :name="item.key"
      />
    </el-tabs>

    <el-card shadow="never" class="border-0">
      <Search @search="getData" @reset="resetSearchForm" :model="searchForm">
        <search-item label="关键词" prop="no">
          <el-input v-model="searchForm.title" placeholder="订单编号" clearable />
        </search-item>
        <template #show>
          <search-item label="收获人" prop="name">
            <el-input v-model="searchForm.name" placeholder="收货人" clearable />            
          </search-item>
          <search-item label="手机号" prop="phone">
            <el-input v-model="searchForm.phone" placeholder="手机号" clearable />            
          </search-item>
          <search-item label="开始时间" prop="create_time">
            <el-date-picker v-model="searchForm.create_time" type="date" style="width: 90%" placeholder="开始时间" 
              value-format="YYYY-MM-DD"/>
          </search-item>
          <search-item label="结束时间" prop="end_time">
            <el-date-picker v-model="searchForm.end_time" type="date" style="width: 90%" placeholder="结束时间" 
              value-format="YYYY-MM-DD"/>
          </search-item>
        </template>
      </Search>

      <list-header layout="refresh,download" @refresh="getData" @download="handleExportExcel">
        <el-button size="small" @click="handleMultiDelete" type="danger">
          批量删除
        </el-button>
      </list-header>

      <el-table ref="multipleTableRef" :data="tableData" stripe style="width: 100%" v-loading="loading" 
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column label="商品" width="300">
          <template #default="{ row }">
            <div class="flex text-sm">
              <div class="flex-1">
                <p>订单号：</p>
                <small>{{ row.no }}</small>
              </div>
              <div>
                <p>下单时间：</p>
                <small>{{ row.create_time }}</small>
              </div>
            </div>

            <div class="flex py-2" v-for="(item, index) in row.order_items" :key="index">
              <el-image :src="item?.cover ?? ''" fit="cover" :lazy="true" style="width: 30px; height: 30px"/>
              <p class="text-blue-500">{{ row.goods_item ? item.goods_item.title : '商品也被删除' }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="实际付款" width="80" prop="total_price" align="center"/>
        <el-table-column label="卖家" width="120" align="center">
          <template #default="{ row }"> 
            <p>{{ row.user.nickname || row.user.username }}</p>
            <small>(用户ID：{{ row.user.id }})</small>
          </template>
        </el-table-column>
        <el-table-column label="交易状态" width="170" align="center">
          <template #default="{ row }">
            <div>
              付款状态：
              <el-tag type="success" size="small" v-if="row.payment_method === 'wechat'">微信支付</el-tag>
              <el-tag type="primary" size="small" v-else-if="row.payment_method === 'alipay'">支付宝支付</el-tag>
              <el-tag type="info" size="small" v-else>未支付</el-tag>
            </div>
            
            <div>
              发货状态：
              <el-tag :type="row.ship_data ? 'success' : 'info'" size="small">{{ row.ship_data ? '已发货' : '未发货' }}</el-tag>
            </div>
            
            <div>
              收货状态：
              <el-tag :type="row.ship_status ? 'success' : 'info'" size="small">{{ row.ship_status ? '已收货' : '未收货' }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button class="px-1" type="primary" text size="small" @click="openInfoModal(row)">订单详情</el-button>
            <el-button v-if="searchForm.tab === 'noship'" class="px-1" type="primary" text size="small" @click="">订单发货</el-button>
            <el-button v-if="searchForm.tab === 'refunding'" class="px-1" type="primary" text size="small" 
              @click="handleRefund(row.id, 1)">同意退款</el-button>
            <el-button v-if="searchForm.tab === 'refunding'" class="px-1" type="primary" text size="small" 
              @click="handleRefund(row.id, 0)">解决退款</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="flex items-center justify-center mt-5">
        <el-pagination background layout="prev, pager, next" :total="total" :current-page="currentPage"
          :page-size="limit" @current-change="getData"/>
      </div>
    </el-card>

    <ExportExcel ref="exportExcelRef" :tabs="tabbars"/>
    <InfoModal ref="infoModalRef" :info="info"/>
  </div>
</template>

<script setup>
  import { ref } from 'vue'
  import {
    getOrderListApi,
    deleteOrderApi,
    shipOrderApi,
    refundOrderApi,
    exportOrderApi,
    getShipInfoApi
  } from '@/api/order.js'

  import ListHeader from '@/components/ListHeader.vue'
  import Search from '@/components/Search.vue'
  import SearchItem from '@/components/SearchItem.vue'
  import { useInitTable } from '@/hooks/useCommon.js'
  import { showModal, toast, showPrompt } from '@/utils'
  import ExportExcel from './components/ExportExcel.vue'
  import InfoModal from './components/InfoModal.vue'

  const {
    searchForm,
    resetSearchForm,
    tableData,
    loading,
    currentPage,
    total,
    limit,
    getData,
    handleDelete,
    handleStatusChange,
    handleSelectionChange,
    handleMultiDelete,
    multipleTableRef,
    multiSelectionIds
  } = useInitTable({
    // 搜索需要的参数
    searchForm: {
      no: '',
      tab: 'all',
      starttime: '',
      endtime: '',
      name: '',
      phone:'',
    },
    // 获取表单的api
    getlist: getOrderListApi,
    delete: deleteOrderApi,
    // 获取表单成功的回调
    onGetListSuccess: (res) => {
      tableData.value = res.list.map((o) => {
        return o
      })
      total.value = res.totalCount
    },
  })

  const tabbars = ref([
    { name:"全部",key:"all"},
    { name:"待付款",key:"nopay" },
    { name:"待发货",key:"noship"},
    { name:"已发货",key:"shiped" },
    { name:"已收货",key:"received" },
    { name:"已完成",key:"finish" },
    { name:"已关闭",key:"closed" },
    { name:"退款中",key:"refunding" },
  ])

  const exportExcelRef = ref(null)
  function handleExportExcel() {
    exportExcelRef.value.open()
  }

  const info = ref(null)
  const infoModalRef = ref(null)
  function openInfoModal(row) {
    row.order_items = row.order_items.map(o => {
      if(o.skus_type == 1 && o.goods_skus) {
        let s = []
        for (const k in o.goods_skus.skus) {
          s.push(o.goods_skus.skus[k].value)
        }
        o.sku = s.join(',')
      }

      return o
    })
    info.value = row
    infoModalRef.value.open(row)
  }

  // 退款处理
  function handleRefund(id, agree) {
    (agree ? showModal('是否同意该订单退款'): showPrompt('请输入解决的理由'))
      .then(({ value }) => {
        let data = { agree }

        if(!agree) {
          data.disagree_reason = value
        }
        refundOrderApi(id, data)
          .then(res => {
            getData()
            toast('操作成功')
          })
      })
  }
</script>

<style scoped>
  .avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }

  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
</style>
